package com.dhq.myapp.presenter.base

import android.content.Context
import com.dhq.myapp.base.BaseActivity
import com.dhq.myapp.base.BaseFragment
import java.lang.ref.WeakReference

/**
 * DESC
 * Created by douhaoqiang on 2025/10/17.
 */

open class MvpPresenter<V>(view: V?) : IMvpPresenter<V?> {
    protected var mContext: Context? = null

    private var viewRef: WeakReference<V?>? = null

    init {
        attachView(view)
        if (view != null && view is BaseActivity) {
            mContext = view as BaseActivity
            (view as BaseActivity).addPresenter(this)
        } else if (view != null && view is BaseFragment) {
            mContext = (view as BaseFragment).getActivity()
            (view as BaseFragment).addPresenter(this)
        }
    }

    public override fun attachView(view: V?) {
        viewRef = WeakReference<V?>(view)
    }

    public override fun detachView(saveInstance: Boolean) {
        if (viewRef != null) {
            viewRef!!.clear()
            viewRef = null
        }
    }

    fun getView(): V? {
        return if (viewRef == null) null else viewRef!!.get()
    }

    fun isViewAttached(): Boolean {
        return viewRef != null && viewRef!!.get() != null
    }
}
